#include "Socket.hpp"
#include <unistd.h>
#include <string>

class TcpServer
{
public:
    TcpServer(uint16_t port)
        :_port(port), _isRunning(false)
    {}

    bool Init()
    {
        _listenSocket.Sock();
        if (!_listenSocket.Bind(_port)) {
            return false;
        }
        return _listenSocket.Listen();
    }

    bool Start()
    {
        _isRunning = true;
        while (_isRunning)
        {
            std::string ip;
            uint16_t port = 0;
            int connFd = _listenSocket.Accept(&ip, &port);
            if (connFd < 0) {
                return false;
            }
            // handle the connection
            HandleConnection(connFd);
            close(connFd);
        }
        _isRunning = false;
        return true;
    }

    virtual ~TcpServer()
    {
        _isRunning = false;
        _listenSocket.Close();
    }

private:
    bool HandleConnection(int connFd)
    {
        char inBuffer[64]; inBuffer[0] = 0;
        ssize_t n = read(connFd, inBuffer, sizeof(inBuffer) - 1);
        inBuffer[n] = 0;
        std::cout << "Echo# " << inBuffer << std::endl;
        std::string outBUffer;
        outBUffer = "Echo# " + std::string(inBuffer);
        if (write(connFd, outBUffer.c_str(), outBUffer.size()) < 0) {
            return false;
        }
        return true;
    }

private:
    Socket _listenSocket;
    bool _isRunning;
    uint16_t _port;
};